<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #tableTitle>
        <span>遥测</span>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleAdd">添加遥测数据</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: ICON.DELETE,
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AddModal @register="registerAddModal" @success="handleSuccess" />
    <DeleteModal @register="registerDeleteModal" @success="handleSuccess" />
  </div>
</template>
<script setup lang="ts">
  import { defineProps, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { Alert, Tooltip } from 'ant-design-vue';
  import { ICON } from '/@/enums/iconEnum';
  import Icon from '/@/components/Icon';
  import { telemetryTableSchema, formSchema } from './index.data';
  import { useModal } from '/@/components/Modal';
  import { ref } from 'vue';
  import AddModal from '../attributeTable/components/Modal.vue';
  import DeleteModal from './components/DeleteModal.vue';
  import { saveEntityTelemetry, deleteEntityTelemetry } from '/@/api/thingsborad/entity/entity';
  import { saveTelemetryParams } from '/@/api/thingsborad/entity/model/entityModel';
  import {
    publicDrawerTableFormStyleSetting,
    tableStyleSetting,
  } from '/@/settings/thingsBoardDesign';
  import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket';

  const ws = useWebsocketStoreWithOut();
  const props = defineProps({
    isComponent: {
      type: Boolean,
      default: true,
    },
    entityType: {
      type: String,
      default: '',
    },
    entityId: {
      type: String,
      default: '',
    },
  });
  // 表格初始数据
  const tableData = ref<any>();
  // 多选参数
  const checkedKeys = ref<any>([]);
  const [registerTable, { setProps, getDataSource, getForm, setTableData }] = useTable({
    ...tableStyleSetting,
    pagination: { pageSizeOptions: ['10', '20', '30'] },
    formConfig: {
      layout: 'horizontal',
      schemas: formSchema,
      ...publicDrawerTableFormStyleSetting,
      actionColOptions: {
        md: { span: 12, offset: 0 },
        lg: { span: 8, offset: 8 },
        xl: { span: 6, offset: 12 },
        xxl: { span: 6, offset: 16 },
      },
      submitFunc: () => {
        const { getFieldsValue } = getForm();
        const { keyName } = getFieldsValue();
        if (Boolean(keyName)) {
          const data = getDataSource().filter(
            (item) => item.key.includes(keyName) || item.value.includes(keyName),
          );
          setTableData(data);
        } else {
          setTableData(tableData.value);
        }
      },
      resetFunc: () => {
        setTableData(tableData.value);
      },
    },

    rowKey: 'key',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  const [registerAddModal, { openModal: openAddModal }] = useModal();
  const [registerDeleteModal, { openModal: openDeleteModal }] = useModal();

  // 添加
  const handleAdd = () => {
    openAddModal(true, { mode: 'add' });
  };

  // 删除
  function handleDelete(record: Recordable) {
    openDeleteModal(true, {
      key: record.key,
      mode: 'delete',
    });
  }

  // 多选
  function onSelect(record: Recordable, selected: boolean) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.key];
    } else {
      checkedKeys.value = checkedKeys.value.filter((key: any) => key !== record.key);
    }
  }
  // 全选
  function onSelectAll(selected: boolean, _selectedRows: Recordable[], changeRows: Recordable[]) {
    const changeIds = changeRows.map((item) => item.key);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((key) => {
        return !changeIds.includes(key);
      });
    }
  }

  // 多选删除
  const handleSelectedDelete = () => {
    openDeleteModal(true, {
      key: checkedKeys.value,
      mode: 'deleteAll',
    });
  };

  // 成功
  const handleSuccess = async ({ key, keys, values }) => {
    if (key == 'add') {
      let telemetryParams: saveTelemetryParams = {
        entityType: props.entityType,
        entityId: props.entityId,
        key: values.keyName,
      };
      switch (values.valueType) {
        case 'string':
          telemetryParams.value = values.stringValue;
          break;
        case 'integer':
          telemetryParams.value = values.integerValue;
          break;
        case 'decimal':
          values.decimalValue = parseFloat(values.decimalValue);
          telemetryParams.value = values.decimalValue;
          break;
        case 'boolean':
          telemetryParams.value = values.booleanValue;
          break;
        case 'json':
          values.jsonValue = JSON.parse(values.jsonValue);
          telemetryParams.value = values.jsonValue;
          break;
      }
      await saveEntityTelemetry(telemetryParams);
      unSubscribe();
      initTelemetryTableData();
    } else {
      let params = {
        entityType: props.entityType,
        entityId: props.entityId,
        obj: {
          keys: keys,
          deleteAllDataForKeys:
            values.deleteStrategy == 'DeleteAllData' ||
            values.deleteStrategy == 'DeleteAllDataExceptLatestValue',
          rewriteLatestIfDeleted: Boolean(values.rewrite),
          deleteLatest:
            Boolean(values.deleteStrategy == 'DeleteAllData') ||
            Boolean(values.deleteStrategy == 'DeleteLatestValue') ||
            Boolean(values.deleteStrategy == 'DeleteAllDataForTimePeriod'),
        },
      };
      await deleteEntityTelemetry(params);
      unSubscribe();
      initTelemetryTableData();
      if (key == 'delete') {
        checkedKeys.value = checkedKeys.value.filter((key: any) => key !== keys);
      } else if (key == 'deleteAll') {
        checkedKeys.value = [];
      }
    }
  };

  // ws取消订阅
  const unSubscribe = () => {
    ws.send(
      ws.getCmdId,
      {
        tsSubCmds: [
          {
            cmdId: ws.getCmdId,
            entityId: props.entityId,
            entityType: props.entityType,
            scope: 'LATEST_TELEMETRY',
            unsubscribe: true,
          },
        ],
      },
      () => {},
    );
  };

  // ws订阅消息
  const initTelemetryTableData = () => {
    ws.send(
      ws.getAndIncrementCmdId(),
      {
        tsSubCmds: [
          {
            cmdId: ws.getCmdId,
            entityId: props.entityId,
            entityType: props.entityType,
            scope: 'LATEST_TELEMETRY',
          },
        ],
      },
      (data: any) => {
        let telemetryTableData: Array<any> = [];
        Object.keys(data.data).forEach((item) => {
          telemetryTableData.push({
            lastUpdateTs: data.data[item][0][0],
            key: item,
            value: data.data[item][0][1],
          });
        });
        setProps({
          columns: telemetryTableSchema,
          dataSource: telemetryTableData,
          loading: false,
        });
        tableData.value = telemetryTableData;
      },
    );
  };

  onMounted(() => {
    initTelemetryTableData();
  });
</script>
